package com.atguigu.dataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.junit.Test;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author hjwStrart
 * @time 2022-03-09 22:26
 * @description com.atguigu.dataSource
 * @version: 1.0
 */
public class DBCP {

//    方式一
    @Test
    public void test1() throws SQLException {
//        获取DBCP数据库连接池
        BasicDataSource dataSource = new BasicDataSource();
//        设置数据库四要素
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///test?serverTimezone=UTC");
        dataSource.setUsername("root");
        dataSource.setPassword("hjw123..");
        Connection conn = dataSource.getConnection();
        System.out.println(conn);
    }

    @Test
//    方式二：使用配置文件    在使用使需要和静态代码块配合使用，不然每次调用给方法都创建了一个数据库连接池
    public void test2() throws Exception {
        Properties properties = new Properties();
        InputStream is = ClassLoader.getSystemResourceAsStream("dbcp.properties");
        properties.load(is);
        DataSource dataSource = BasicDataSourceFactory.createDataSource(properties);
        Connection conn = dataSource.getConnection();
        System.out.println(conn);
    }
}
